import random
import time
from openpyxl import Workbook,load_workbook

account_list = []   # 账号表，防止重复
file_local = '../银行表.xlsx'
bank_name = "中国工商银行昌平支行"

# 整数输入：long为多参数时仅计算前两个，[0]为最小范围，[1]为最大范围
# # # # # 最终呈现效果为[long[0]:long[1]]
# # # # # 当long仅为单个数据,则为定长
'''返回值类型：int'''
def inINT(msg, *long):
    while True:
        a = input(msg)  # 获取
    # 长度要求
        if (len(long) > 1):
            long_min = long[0]
            long_max = long[1]
            if (len(a) >= long_min and len(a) <= long_max and a.isdigit()):
                return int(a)
            print(f'请输入{long_min}~{long_max}位整数')
    # 定长
        else:
            long_solid = long[0]
            if (len(a) == long_solid and a.isdigit()):
                return int(a)
            print(f'请输入{long_solid}位整数')

def inSTR(msg, *long):
    while True:
        a = input(msg)  # 获取
    # 长度要求
        if (len(long) > 1):
            long_min = long[0]
            long_max = long[1]
            if (len(a) >= long_min and len(a) <= long_max):
                return str(a)
            print(f'请输入{long_min}~{long_max}位字符')
    # 定长
        else:
            long_solid = long[0]
            if (len(a) == long_solid):
                return str(a)
            print(f'请输入{long_solid}位字符')


'''//////////////////////////////////////////////////////'''
# 地址注册 //国家(str)、省份(str)、街道(str)、门牌号(str)
def address_select():
    print('---地址注册:=====')
    nation = inSTR('国家>>>', 0, 20)
    province = inSTR('省份>>>', 0, 20)
    street = inSTR('街道>>>', 0, 20)
    door = inSTR('门牌号>>', 0, 50)
    location = [nation, province, street, door]

    return location

# 开户
def account_init(bank):

    dict = {}

    print("欢迎开户》》》》》》")
    user_name = inSTR('请输入用户名>>', 0, 20)
    password = inINT('请输入密码>>', 6)
    bank_name = bank
    init_gold = 0
    address = address_select()
    date = time.strftime('%Y-%m-%d %H:%M:%S')
# 账户标识由8位数字构成，作为主键，互不相同
    account_list = inACCOUNT()
    print(account_list)
    while True:
        account_num = random.randint(10000000, 100000000)
    # 判断是否重复，不重复则记录数据，且用户上限100
        flag = maxACCOUNT(100)
        if (account_num not in account_list) and flag:
            dict.setdefault(account_num, '')
            dict[account_num] = {'用户名':user_name,'密码':password,'开户信息':(bank_name,date),'存款余额':init_gold,'地址':address}
            print('《《《《《《感谢使用')
            putDATA(dict)
            return True
        elif not flag:
            return False

# 存入
def countIN(account, gold):
    wb = load_workbook(file_local)
    sheet = wb['Sheet']
    i = 0
    for row in sheet.values:
        i += 1
        if(row[0] == account):
            gold += row[5]
            print('充值成功', i)
            sheet.cell(row=i, column=6, value=gold)
            wb.save('银行表.xlsx')
            return True

    print("未找到账号")
    return False

# 取钱
def countOUT(account, password, gold):
    wb = load_workbook(file_local)
    sheet = wb['Sheet']
    i = 0
    for row in sheet.values:
        i += 1
        if (row[0] == account):
            if(password == row[2]):
                if(gold <= row[5]):
                    gold = row[5]-gold
                    sheet.cell(row=i, column=6, value=gold)
                    wb.save('银行表.xlsx')
                    print('取出成功')
                    return 0

                print('余额不足')
                return 3

            print('密码错误')
            return 2

    print("用户不存在")
    return 1

# 转账
def transfer(account1, password, account2, gold):
    wb = load_workbook(file_local)
    sheet = wb['Sheet']
    i = 0
    j = 0
    list = []
    for row in sheet.values:
        i += 1
        list.append(row[0])
        list.append((row[2], row[5], i))

    if (account1 in list) and (account2 in list):
        for i in range(len(list)):
            if(list[i] == account1):
                if(list[i+1][0] == password):
                    if (gold <= list[i+1][1]):
                        gold1 = list[i+1][1] - gold
                        sheet.cell(row=list[i+1][2], column=6, value=gold1)
                    else:
                        print('余额不足')
                        return 3
                else:
                    print('密码错误')
                    return 2
            elif(list[i] == account2):
                j = list[i+1][2]
                gold2 = list[i+1][1]
        sheet.cell(row=j, column=6, value=gold2+gold)
        wb.save('银行表.xlsx')

        print('转入成功')
        return 0

    print('账户不存在')
    return 1

# 查询账户
def checkMSG(account, password):
    wb = load_workbook(file_local)
    sheet = wb['Sheet']
    i = 0
    for row in sheet.values:
        i += 1
        if (row[0] == account):
            if (password == row[2]):
                info = ('''
+——————————————————————————————————————
|           当前账号：%s      
|          ————————————————
|            用户名：%s
|              密码：%d
|              余额：%.2f
|              住址：%s
|         -----------------
|           开户时间：%s
|           开户银行：%s
|
+——————————————————————————————————————
                ''')


            print(info % (row[0],row[1],row[2],row[5],row[6]+row[7]+row[8]+row[9],row[4],row[3]))
            return 2

    print("用户不存在")
    return 1


'''///////////////////////////////////////////'''
# 用于将数据写入表单
def putDATA(account_dict):
    wb = load_workbook(file_local)
    sheet = wb['Sheet']
    list = []
    for item in account_dict:
        list.append(item)
        list.append(account_dict[item]['用户名'])
        list.append(account_dict[item]['密码'])
        list.append(account_dict[item]['开户信息'][0])
        list.append(account_dict[item]['开户信息'][1])
        list.append(account_dict[item]['存款余额'])
        list.append(account_dict[item]['地址'][0])
        list.append(account_dict[item]['地址'][1])
        list.append(account_dict[item]['地址'][2])
        list.append(account_dict[item]['地址'][3])
        print(list, account_dict)
        sheet.append(list)

    wb.save('银行表.xlsx')

# 读取表单
def inACCOUNT():
    wb = load_workbook(file_local)
    sheet = wb['Sheet']
    list = []
    flag = 0
    for i in sheet.values:
        if(flag == 0):
            flag = 1
            continue
        list.append(i[0])
    return list

# 用户最大量检测
def maxACCOUNT(n):
    wb = load_workbook(file_local)
    sheet = wb['Sheet']
    if (sheet.max_row > n):
        print("账户已达上限(%d)" % n)
        return False
    return True

def UI():
    while True:
        print(r'''
         +-—————————————————————————————————
        /    中国工商银行账户管理系统 V1.0    
       / --------------------------------
      /              1.开户            
     /              2.存钱            
    /              3.取钱            
   /              4.转账             
  /              5.查询              
 /              6.Bye！              
/                                
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
    ''')
        t = time.time()
        flag = inINT(">>",1)

        if(flag == 1):
            account_init(bank_name)
        elif(flag == 2):
            print("存钱")
            a = input('请输入用户号码：')
            b = input('请输入金额：')
            countIN(int(a), float(b))
        elif(flag == 3):
            print("取钱")
            a = input('请输入用户号码：')
            b = input('请输入密码：')
            c = input('请输入金额：')
            countOUT(int(a), int(b), float(c))
        elif(flag == 4):
            print("转账")
            a = input('请输入转出用户：')
            b = input('请输入密码：')
            c = input('请输入转入用户：')
            d = input('请输入金额：')
            transfer(int(a), int(b), int(c), float(d))
        elif(flag == 5):
            print("查询")
            a = input('请输入用户号码：')
            b = input('请输入密码：')
            checkMSG(int(a), int(b))
        elif(flag == 6):
            return



        print('\n——执行完成/所用时间:%fs' % (time.time() - t))
        input('---------按任意键继续......')

UI()

